﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using Newtonsoft.Json.Serialization;

namespace Best.SmartCms.Utility.JsonFormater
{
    public class CustomizeDefaultResolver : CamelCasePropertyNamesContractResolver
    {
        protected override JsonContract CreateContract(Type objectType)
        {
            var contract = base.CreateContract(objectType);
            if (objectType == typeof(DateTime) || objectType == typeof(DateTime?))
            {
                contract.Converter = new CustomizeDateTimeConverter();
            }

            if (objectType == typeof(Guid) || objectType == typeof(Guid?))
            {
                contract.Converter = new CustomizeGuidConverter();
            }

            return contract;
        }

        protected override IValueProvider CreateMemberValueProvider(MemberInfo member)
        {
            var provider = base.CreateMemberValueProvider(member);

            if (member.MemberType == MemberTypes.Property)
            {
                Type propType = ((PropertyInfo)member).PropertyType;
                if (propType.BaseType != null && propType.IsAssignableFrom(typeof(string)))
                {
                    return new StringValueProvider(provider, propType);
                }

            }

            return provider;
        }
    }


    class StringValueProvider : IValueProvider
    {
        private IValueProvider innerProvider;
        private object defaultValue;

        public StringValueProvider(IValueProvider innerProvider, Type stringType)
        {
            this.innerProvider = innerProvider;
            defaultValue = string.Empty;
        }

        public object GetValue(object target)
        {
            return innerProvider.GetValue(target) ?? defaultValue;
        }

        public void SetValue(object target, object value)
        {
            innerProvider.SetValue(target, value ?? defaultValue);
        }
    }

   
}
